<template>
	<div class="app-container">
		<div class="wrapper">
			<h4>导入各类参数信息</h4>
			<el-row class="row-bgs" justify="start">
				<el-col :span="8">
					<div class="buildVulner" @click="importParmsClick('buildVulner')"></div>
				</el-col>
				<el-col :span="8">
					<div class="brickStructure" @click="importParmsClick('brickStructure')"></div>
				</el-col>
				<el-col :span="8">
					<div class="reinforConcrete" @click="importParmsClick('reinforConcrete')"></div>
				</el-col>
			</el-row>
			<el-row class="row-bgs" justify="start">
				<el-col :span="8">
					<div class="highBuilding" @click="importParmsClick('highBuilding')"></div>
				</el-col>
				<el-col :span="8">
					<div class="hubBuilding" @click="importParmsClick('hubBuilding')"></div>
				</el-col>
				<!-- <el-col :span="8">
					<div class="seismicAnalysis" @click="importParmsClick('seismicAnalysis')"></div>
				</el-col> -->
			</el-row>

			<!-- 导入建筑物易损性信息 -->
			<el-dialog v-if="outerVisible" v-model="outerVisible" title="导入数据" :close-on-click-modal="false" destroy-on-close width="30%">
				<template #default>
					<el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
						<el-form-item label="单个/批量：" prop="import">
							<el-radio-group v-model="ruleForm.import">
								<el-radio label="1">单个导入</el-radio>
								<el-radio label="2">批量导入</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item label="矩阵/曲线：" prop="buildVulner">
							<el-radio-group v-model="ruleForm.buildVulner">
								<el-radio label="1">建筑物易损性矩阵</el-radio>
								<el-radio label="2">建筑物易损性曲线</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-form>
					<div class="downloadModel">下载导入模板<span @click="importTemplate(1)">{{ templateFileName }}</span></div>
					<el-upload ref="uploadRef1" :action="uploadFileUrl" :before-upload="beforeUpload"
						:before-remove="beforeRemove" :on-success="uploadSuccess" :on-error="uploadError"
						:file-list.sync="fileList" :headers="headers" :multiple="false" :limit="1" :auto-upload="false">
						<el-button type="primary" class="icon-Angle-upload">选择本地文件</el-button>
					</el-upload>
				</template>
				<template #footer>
					<span class="dialog-footer">
						<el-button type="primary" @click="onSubmit(ruleFormRef)">确定</el-button>
						<el-button @click="outerVisible = false">取消</el-button>
					</span>
				</template>
			</el-dialog>
			<!-- 基础信息弹框 -->
			<el-dialog v-if="innerVisible" v-model="innerVisible" title="基本信息" :close-on-click-modal="false" width="80%">
				<el-form :inline="true" ref="BasicFromRef" :rules="rules" label-position="right" :model="params"
					label-width="200px" style="margin-top: 20px;">
					<el-row justify="center">
						<el-col :span="11">
							<el-form-item label="编号：" class="form-item" prop="number">
								<el-input v-model="params.number" placeholder="" :disabled="true" clearable />
							</el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item label="结构类型：" class="form-item" prop="structureType">
								<el-col :span="12">
									<el-form-item prop="structureType">
										<el-select v-model="params.structureType" placeholder="请选择" class="form-select"
											@change="structureTypeChange" clearable>
											<el-option v-for="item in structureTypeOptions" :key="item.value"
												:label="item.label" :value="item.value"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="1" class="text-center"><span class="text-gray-500">-</span></el-col>
								<el-col :span="11">
									<el-form-item prop="structureType1">
										<el-select v-model="params.structureType1" placeholder="请选择" class="form-select"
											clearable>
											<el-option v-for="item in structureType1Options" :key="item.value"
												:label="item.label" :value="item.value"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="center">
						<el-col :span="11">
							<el-form-item label="区域：" class="form-item" prop="province">
								<el-form-item prop="province" style="width:120px;margin-right:10px;">
									<el-select v-model="params.province" placeholder="请选择省" @change="chooseProvince"
										clearable value-key="id">
										<el-option v-for="item in provinceData" :key="item.id" :label="item.name"
											:value="item"></el-option>
									</el-select>
								</el-form-item>
								<el-form-item prop="city" style="width:120px;margin-right:10px;">
									<el-select v-model="params.city" placeholder="请选择市" @change="chooseCity" clearable
										value-key="id">
										<el-option v-for="item in cityData" :key="item.id" :label="item.name"
											:value="item"></el-option>
									</el-select>
								</el-form-item>
								<el-form-item prop="county" style="width:120px;">
									<el-select v-model="params.county" placeholder="请选择县" @change="chooseCounty" clearable
										value-key="id">
										<el-option v-for="item in areaData" :key="item.id" :label="item.name"
											:value="item"></el-option>
									</el-select>
								</el-form-item>
							</el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item label="设防情况：" class="form-item" prop="fortification">
								<el-select v-model="params.fortification" placeholder="请选择" class="form-select" clearable>
									<el-option v-for="item in fortificationOptions" :key="item.value" :label="item.label"
										:value="item.value">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="center">
						<el-col :span="11">
							<el-form-item label="年代：" class="form-item" prop="years">
								<el-select v-model="params.years" placeholder="请选择" class="form-select" clearable>
									<el-option v-for="item in yearsOptions" :key="item.value" :label="item.label"
										:value="item.value">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item label="维护人：" class="form-item" prop="userName">
								<el-input v-model="params.userName" placeholder="" clearable />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="center">
						<el-col :span="11">
							<el-form-item label="层数：" class="form-item" prop="cs">
								<el-select v-model="params.cs" placeholder="请选择" class="form-select" clearable :disabled="disabledcs">
									<el-option v-for="item in csOptions" :key="item.value" :label="item.label"
										:value="item.value">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item label="维护时间:" class="form-item" prop="createTime">
								<el-date-picker v-model="params.createTime" type="date" placeholder="选择日期">
								</el-date-picker>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="center">
						<el-col :span="11">
							<el-form-item label="用途：">
								<el-col :span="12">
									<el-form-item prop="use0">
										<el-select v-model="params.use0" placeholder="请选择" class="form-select"
											@change="useChange" clearable>
											<el-option v-for="item in useOptions" :key="item.value" :label="item.label"
												:value="item.value"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="1" class="text-center"><span class="text-gray-500">-</span></el-col>
								<el-col :span="11">
									<el-form-item prop="use1">
										<el-select v-model="params.use1" placeholder="请选择" class="form-select" clearable>
											<el-option v-for="item in use1Options" :key="item.value" :label="item.label"
												:value="item.value"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
							</el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item label="维护人所属单位：" class="form-item" prop="maintainerUnit">
								<el-input v-model="params.maintainerUnit" placeholder="" clearable />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="center" v-show="isIM">
						<el-form-item label="请输入IM范围：">
							<el-col :span="8">
								<el-form-item label="起始IM值" prop="startImValue">
									<el-input-number v-model="params.startImValue" :min="0.01" :max="2"
										:step="params.selfIncreasingSpan" clearable />
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="结束IM值" prop="endImValue">
									<el-input-number v-model="params.endImValue" :min="0.01" :max="2"
										:step="params.selfIncreasingSpan" clearable />
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="自增跨度" prop="selfIncreasingSpan">
									<el-input-number v-model="params.selfIncreasingSpan" :min="0" :max="2" :step="0.01"
										clearable />
								</el-form-item>
							</el-col>
						</el-form-item>
					</el-row>
				</el-form>
				<template #footer>
					<div class="dialog-footer">
						<el-button type="primary" @click="onSubmitForm(BasicFromRef)">确定</el-button>
						<el-button @click="innerVisible = false">取消</el-button>
					</div>
				</template>
			</el-dialog>

			<!-- 导入其它信息 -->
			<el-dialog v-if="dialogVisible" v-model="dialogVisible" title="导入数据" :close-on-click-modal="false" width="30%">
				<div class="downloadModel">下载导入模板<span @click="importTemplate()">{{ downloadFileName }}</span></div>
				<el-upload ref="uploadRef" :action="uploadFileUrl" :before-upload="beforeUpload"
					:before-remove="beforeRemove" :on-success="uploadSuccess" :on-error="uploadError"
					:file-list.sync="fileList" :headers="headers" :multiple="false" :limit="1" :auto-upload="false">
					<el-button type="primary" class="icon-Angle-upload">选择本地文件</el-button>
				</el-upload>
				<template #footer>
					<span class="dialog-footer">
						<el-button type="primary" @click="submitUpload">确定</el-button>
						<el-button @click="cancleUpload">取 消</el-button>
					</span>
				</template>
			</el-dialog>


			<!-- 枢纽建筑参数信息 -->
			<el-dialog v-if="buildVisible" v-model="buildVisible" title="导入数据" :close-on-click-modal="false" width="700px">
				<template #default>
					<p></p>
					<el-form ref="ruleFormBuildRef" :model="ruleForm" :rules="rules1" label-width="120px">
						<el-form-item label="类别" prop="type">
							<el-select v-model="ruleForm.type" placeholder="请选择" @change="changeTypeOption" clearable
								value-key="name">
								<el-option v-for="item in typeOption" :key="item.code" :label="item.name"
									:value="item.code">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="省" prop="province">
							<el-select v-model="ruleForm.province" placeholder="请选择" @change="chooseProvince" clearable
								value-key="name">
								<el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="市" prop="city">
							<el-select v-model="ruleForm.city" placeholder="请选择" @change="chooseCity" clearable
								value-key="name">
								<el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="区/县" prop="county">
							<el-select v-model="ruleForm.county" placeholder="请选择" @change="chooseCounty" clearable
								value-key="name">
								<el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item">
								</el-option>
							</el-select>
						</el-form-item>
						<!-- <el-form-item label="结构类型" prop="structureType1">
							<el-select v-model="ruleForm.structureType1" placeholder="请选择" @change="structureTypeChange1" clearable>
								<el-option v-for="item in structureTypeOptions1" :key="item.value" :label="item.label"
								:value="item.value">
								</el-option>
							</el-select>
							&nbsp;—&nbsp;
							<el-select v-model="ruleForm.structureType2" placeholder="请选择" clearable>
								<el-option v-for="item in structureType1Options1" :key="item.value" :label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
						</el-form-item> -->
					</el-form>
					<div class="downloadModel">下载导入模板<span @click="importTemplate(2)">{{ templateFileName1 }}</span></div>
					<div style="display: flex;">
						<div class="new-fileBtn">
							<input type="file" @change="uploadFileChange" style="width: 70px;" id="excel-button-selectfile"
								accept=".xls,.xlsx" />
						</div>
						<div class="new-filesTextArea">
							<el-input type="textarea" :rows="4" v-model="textarea" readonly></el-input>
						</div>
					</div>

					<!-- <el-upload ref="uploadRef1" :action="uploadFileUrl" :before-upload="beforeUpload" :before-remove="beforeRemove"
						:on-success="uploadSuccess" :on-error="uploadError" :file-list.sync="fileList" :headers="headers"
						:multiple="false" :limit="1" :auto-upload="false" v-if="buildVisible">
						<el-button type="primary" class="icon-Angle-upload">选择本地文件</el-button>
					</el-upload> -->
				</template>
				<template #footer>
					<span class="dialog-footer">
						<el-button type="primary" @click="onSubmitBuild()">上传</el-button>
						<el-button @click="buildVisible = false">取消</el-button>
					</span>
				</template>
			</el-dialog>

			<!--覆盖的数据版本-->
			<el-dialog v-model="dialogCover" title="请选择要覆盖的数据版本" width="700px" append-to-body :show-close="false"
				:close-on-click-modal="false">
				<h4></h4>
				<el-table class="listTables" ref="multipleTableRef" :data="dataCoverList" stripe style="width: 100%"
					@selection-change="handleSelectionChange" @select="handleSelectClick">
					<el-table-column type="selection" width="55" />
					<el-table-column prop="versionCode" label="版本号" align="center" width="200"></el-table-column>
					<el-table-column prop="createTime" label="上传时间" align="center" width="110"></el-table-column>
					<el-table-column prop="fileName" label="文件名称" align="center" show-overflow-tooltip></el-table-column>
					<el-table-column label="区域" align="center" show-overflow-tooltip>
						<template #default="{row}">
							<span>{{ row.province  }}-{{ row.city }}-{{ row.county }}</span>
						</template>
					</el-table-column>
				</el-table>
				<template #footer>
					<div class="dialog-footer">
						<el-button type="primary" :disabled="!coverId" @click="queryCover">确定覆盖</el-button>
						<el-button @click="uploadData">直接上传</el-button>
					</div>
				</template>
			</el-dialog>
		</div>
	</div>
</template>

<script setup>
import { ref, reactive, computed, watch, } from 'vue';
// 引入接口
import {
	apiUrl, // 数据导入接口路径对象
	saveBvInformation,//添加易损性矩阵信息
	saveBvInformationCurve//添加易损性曲线
} from "@/api/importData/buildingAreaInfo.js";
import { repeatData, uploadBuildExcel } from "@/api/map/disasterDataManagement/lifelineSystemInfo.js";
import { upLoadFile } from "@/api/system/attachFile";
import { getToken } from "@/utils/auth";
import { getProvince, getChildArea } from '@/api/system/division';
import { ElMessage, ElMessageBox } from 'element-plus'
// 公用方法
import { parseTime } from "@/utils/ruoyi.js";
// 引入store
import useUserStore from "@/store/modules/user";
import useDictStore from '@/store/modules/dict';
// 获取pinia
const userStore = useUserStore();
const dictStore = useDictStore();
// 用户名
const userName = computed(() => userStore.name || "");
// 所属机构名称
const orgName = computed(() => userStore.orgName || "");

// 获取当前实例
const { proxy } = getCurrentInstance();
// 设置接口调用的headers
const headers = ref({ token: "token " + getToken() });

// 获取dom
const uploadRef = ref();
const uploadRef1 = ref();
const ruleFormRef = ref();
const BasicFromRef = ref();
// const ruleFormBuildRef = ref();

// 显示弹出框
const dialogVisible = ref(false);
const outerVisible = ref(false);
const innerVisible = ref(false);
const buildVisible = ref(false)

const structureTypeRules = (rule, value, callback) => {
	if (!value) {
		callback(new Error('请选择结构类型！'));
	} else {
		if (structureType1Options1.value.length == 0) {
			callback();
		} else {
			if (!ruleForm.value.structureType2) {
				callback(new Error('请选择二级结构类型！'));
			} else {
				callback();
			}
		}
	}
};

// 选择文件列表
const fileList = ref([]);
// 文件上传接口地址
const uploadFileUrl = ref(apiUrl.uploadBvInformation);
// 导出文件名称
const downloadFileName = ref('建筑物易损性数据模板.xlsx');

const data = reactive({
	// 表单参数
	params: {
		cpviId: '', //id
		number: '', //编号
		province: '', //省
		city: '', //市
		county: '', //县
		use0: '', //用途
		use1: '',
		structureType: '', //结构类型
		structureType1: '', //结构类型
		years: '', //年代
		fortification: '', //设防情况
		cs: '', //层数
		// IM计算参数
		startImValue: undefined,//IM起始值
		endImValue: undefined, //IM终止值
		selfIncreasingSpan: 0.05, //自增跨度
		// 维护人信息
		userName: userName.value, //维护人
		maintainerUnit: orgName.value, //维护人所属单位
		createTime: parseTime(new Date()), //维护时间
	},
	ruleForm: {
		// 1：单个导入，2：批量导入
		import: '',
		// 1：矩阵，2：曲线
		buildVulner: '',
		// 类别
		type: '',
		// 区域
		province: "",
		city: "",
		county: "",
		// 结构类型
		structureType1: '',
		structureType2: '',
	},
	// 表单验证规则
	rules: {
		// number: [{ required: true, message: '请选择', trigger: 'blur' }],
		userName: [{ required: true, message: '请选择', trigger: 'blur' }],
		maintainerUnit: [{ required: true, message: '请选择', trigger: 'blur' }],
		createTime: [{ required: true, message: '请选择', trigger: 'blur' }],
		fortification: [{ required: true, message: '请选择', trigger: 'change' }],
		//years: [{ required: true, message: '请选择', trigger: 'change' }],
		province: [{ required: true, message: '请选择', trigger: 'change' }],
		structureType: [{ required: true, message: '请选择', trigger: 'change' }],
		import: [{ required: true, message: '请选择单个/批量', trigger: 'change' }],
		buildVulner: [{ required: true, message: '请选择矩阵/曲线', trigger: 'change' }]
	},
	rules1: {
		structureType1: [{ required: true, trigger: 'change', validator: structureTypeRules, }],
		type: [{ required: true, message: '请选择', trigger: 'change' }],
		province: [{ required: true, message: '请选择', trigger: 'change' }],
		city: [{ required: true, message: '请选择', trigger: 'change' }],
		county: [{ required: true, message: '请选择', trigger: 'change' }],
	},
	//文件类型
	typeOption: ref([{ code: "11", name: "水厂泵房" }, { code: "12", name: "重要发电厂房" }, { code: "14", name: "燃气-门站/场站" }, { code: "13", name: "基站" }]),
	structureTypeOptions1: ref([]),
	structureType1Options1: ref([]),
	// 设防情况
	fortificationOptions: dictStore.fortificationOptions || [],
	// 年份
	yearsOptions: dictStore.yearsOptions || [],
	// 结构类型
	structureTypeOptions: dictStore.structureTypeOptions || [],
	structureType1Options: [],
	// 用途
	useOptions: dictStore.useOptions || [],
	use1Options: [],
	// 层数
	csOptions: dictStore.csOptions || [],
	// 上传文件中的数据列表
	dataList: [],
});
const {
	// 表单数据
	params,
	//表单验证
	ruleForm,
	// 表单验证规则
	rules,
	rules1,
	typeOption,
	// 结构类型选项
	structureTypeOptions1,
	structureType1Options1,
	// 设防情况选项
	fortificationOptions,
	// 年份选项
	yearsOptions,
	// 结构类型选项
	structureTypeOptions,
	structureType1Options,
	// 用途选项
	useOptions,
	use1Options,
	csOptions,
	dataList,
} = toRefs(data);

// 监听，单个/批量，矩阵/曲线表单的变化
watch(() => ruleForm, (val, old) => {
	// 矩阵
	if (val.value.buildVulner === '1') {
		// 批量
		if (val.value.import === '2') {
			uploadFileUrl.value = apiUrl.uploadBvInformation;
		}
		// 单个
		else {
			uploadFileUrl.value = apiUrl.uploadSingleBvInformation;
		}
	}
	// 曲线
	else if (val.value.buildVulner === '2') {
		// 批量
		if (val.value.import === '2') {
			uploadFileUrl.value = apiUrl.uploadBvInformationCurve;
		}
		// 单个
		else {
			uploadFileUrl.value = apiUrl.uploadSingleBvInformationCurve;
		}
	}
}, {
	immediate: true, //在侦听器创建时立即触发回调
	deep: true, //强制深度遍历
})
// 模板文件名称，导入建筑物易损性信息使用
const templateFileName = computed(() => {
	return `【建筑物易损性信息】易损性${ruleForm.value.buildVulner === '1' ? '矩阵' : '曲线'}（${ruleForm.value.import === '1' ? '单个' : '批量'}导入）.xlsx`;
})

// 其他导入名称
const templateFileName1 = ref('')
// 单个导入建筑物易损性曲线，显示IM范围值，其它不显示
const isIM = computed(() => {
	return ruleForm.value.import === '1' && ruleForm.value.buildVulner === '2' ? true : false;
})


// 其它信息导入，确定按钮事件
const submitUpload = (res) => {
	uploadRef.value?.submit()
}
// 建筑物易损性，导入数据页面，确定按钮事件
const onSubmit = (elemForm) => {
	if (!elemForm) return;
	elemForm.validate((valid, fields) => {
		if (valid) {
			if (fileList.value.length) {
				// 提交文件上传表单
				uploadRef1.value.submit();
			} else {
				proxy.$modal.msgWarning('请选择本地文件！');
			}
		}
	})
}
// 建筑物易损性，文件导入和提交信息，确定按钮事件
const onSubmitForm = (elemForm) => {
	if (!elemForm) return;
	elemForm.validate((valid, fields) => {
		if (valid) {
			// 矩阵
			if (ruleForm.value.buildVulner == '1') {
				// 添加易损性矩阵信息
				onSaveBvInformation().then(res => {
					// 重置表单
					elemForm.resetFields();
					// 关闭所有弹框
					closeAllDialog();
				});
			} else {
				// 添加易损性曲线信息
				onSaveBvInformationCurve().then(res => {
					// 重置表单
					elemForm.resetFields();
					// 关闭所有弹框
					closeAllDialog();
				});
			}
		}
	})
}
// 取消按钮事件
const cancleUpload = (res) => {
	// 关闭所有弹框
	closeAllDialog();
}
// 关闭所有弹框
function closeAllDialog() {
	// 清空文件列表
	dataList.value = [];
	// 更新ruleForm
	ruleForm.value.import = '';
	ruleForm.value.buildVulner = '';
	// 隐藏弹框
	innerVisible.value = false;
	outerVisible.value = false;
	dialogVisible.value = false;
}

//选择文件
const textarea = ref("");//上传文件只读显示文本框
function uploadFileChange() {
	let uploadinputFiles = null;
	uploadinputFiles = document.getElementById("excel-button-selectfile").files;
	textarea.value = uploadinputFiles[0].name;
}

const dialogCover = ref(false); // 覆盖开关
const dataCoverList = ref([]);// 可覆盖版本数据
const coverObj = ref({});// 覆盖参数
const loading = ref(false);
const uploadData = ()=>{
  dialogCover.value = false;
		coverObj.value.append("id", '');
  		coverObj.value.append("cover", '0');
        uploadBuildExcel(coverObj.value).then((response) => {
          nextTick(() => {
            let msg = response.data;
            loading.value = false;
			buildVisible.value = false;
            ElMessageBox.alert(msg, '系统信息', {
              confirmButtonText: '确认',
              type: 'success'
            });
          });
        }).catch(err => {
          loading.value = false;
        });
}
// 覆盖确认
const queryCover = () =>{
  //上传保存数据
  loading.value = true;
  coverObj.value.append("id", coverId.value);
  coverObj.value.append("cover", '1');
  uploadBuildExcel(coverObj.value).then((response) => {
        dialogCover.value = false;
        nextTick(() => {
          let msg = response.data;
          loading.value = false;
          buildVisible.value = false;
          ElMessageBox.alert(msg, '系统信息', {
            confirmButtonText: '确认',
          type: 'success'
      });
    });
  }).catch(err => {
        loading.value = false;
  });
}
const selectionChecked = ref([])
const coverId = ref();
// 获取选中当前行数据
const handleSelectionChange = (checked) => {
  selectionChecked.value = checked;
  if(selectionChecked.value.length==0){
    coverId.value = undefined;
  }else{
    coverId.value = checked[0].id;
  }
}
// 复选框点击触发动作，长度大于1，我们进行取前一个元素，并设置前一个元素的选中状态，那么当前的元素就是可选的一个状态了
const handleSelectClick = (selection) => {
  if (selection.length > 1) {
    const del_row = selection.shift()
    // toggleRowSelection属性的第二个元素接受的是一个选中状态的布尔值，false不选中，true选中；
    proxy.$refs['multipleTableRef'].toggleRowSelection(del_row, false)
  }
}

// 上传建筑物数据
const onSubmitBuild = () => {
	proxy.$refs['ruleFormBuildRef'].validate((valid) => {
		if (valid) {
			if (textarea.value != '') {
				let uploadinput = null;
				uploadinput = document.getElementById("excel-button-selectfile");
				let province = ruleForm.value.province;
				let city = ruleForm.value.city;
				let area = ruleForm.value.county;
				let type = ruleForm.value.type;
				const fileFormData = new FormData();
				fileFormData.append('file', uploadinput.files[0]);
				let fileIds = "";//上传附件id列表
				//上传文件到附件表
				upLoadFile(fileFormData).then(res => {
					// console.log("上传文件成功")
					if (res.code == 200) {
						let resultArr = res.data;
						fileIds += resultArr[0].attachId;
						let formData = new FormData();
						// 是否覆盖
						let cover = '0';
						// 覆盖则传改id
						let id = '';
						// 检验是否覆盖
						formData.append("type", type);
						formData.append("province", province);
						formData.append("city", city);
						formData.append("county", area);
						formData.append('file', uploadinput.files[0]);
						formData.append('fileIds', fileIds);
						loading.value = true;
						coverObj.value = formData;
						repeatData({ name:textarea.value.split('.')[0],type: type, province: province, city: city, county: area,fileIds:fileIds }).then(res => {
							const { code, data } = res;
							if (code == 200) {
								loading.value = false
								if (data.length == 0) {
									formData.append("cover", '0');
									formData.append("id", '');
									// formData.append('file', uploadinput.files[0]);
									//上传保存数据
									loading.value = true;
									uploadBuildExcel(formData).then((response) => {
										loading.value = false
										nextTick(() => {
											let msg = response.data;
											loading.value = false;
											buildVisible.value = false;
											ElMessageBox.alert(msg, '系统信息', {
												confirmButtonText: '确认',
												type: 'success'
											});
										});
									}).catch(err => { loading.value = false })
								} else {
									loading.value = false;
									dataCoverList.value = data;
									dialogCover.value = true;
								}
							} else {
								loading.value = false;
							}

						})

					}
				});
			} else {
				proxy.$modal.msgWarning('请上传文件！')
			}
		}
	});
}

// 行政区划选择
const provinceData = ref([]); //省
const cityData = ref([]); //市
const areaData = ref([]); //区、县
/** 获取省列表 */
function getProvinceData() {
	getProvince().then(response => {
		provinceData.value = response.data;
	});
}
// 选择省
function chooseProvince(value) {
	if (innerVisible.value) {
		params.value.city = null;
		params.value.county = null;
		params.value.province = value.name;
	}
	if (buildVisible.value) {
		ruleForm.value.city = null;
		ruleForm.value.county = null;
		ruleForm.value.province = value.name;
	}
	cityData.value = [];
	areaData.value = [];
	getChildArea(value.id).then(response => {
		cityData.value = response.data;
	});
}
// 选择市
function chooseCity(value) {
	if (innerVisible.value) {
		params.value.city = value.name;
		params.value.county = null;
	}
	if (buildVisible.value) {
		ruleForm.value.city = value.name;
		ruleForm.value.county = null;
	}

	areaData.value = [];
	getChildArea(value.id).then(response => {
		areaData.value = response.data;
	});
}
// 选择区县
function chooseCounty(value) {
	if (innerVisible.value) {
		params.value.county = value.name;
	}
	if (buildVisible.value) {
		ruleForm.value.county = value.name;
	}
}
// 以下结构对应全楼层
const arrStructure = ['钢筋混凝土结构', '钢结构', '组合结构'];
// 结构类型选择
const disabledcs = ref(false);
const structureTypeChange = (val) => {
	const structureTypes = structureTypeOptions.value.find(item => item.value === val);
	// 设置二级预选值
	if (structureTypes) {
		structureType1Options.value = structureTypes.children;
	}
	// 清空选中的二级候选值
	params.value.structureType1 = '';
	// 清空用途
	params.value.use0 = '';
	params.value.use1 = '';
	use1Options.value = [];
	// 设防情况
	params.value.fortification = '';
	fortificationOptions.value = dictStore.fortificationOptions;
	// 年代
	yearsOptions.value = dictStore.yearsOptions;
	// 过滤楼层预选项
	if (val=='钢筋混凝土结构'||val=='钢结构') {
		csOptions.value = dictStore.csOptions;
		disabledcs.value = false;
		// 用途处理
		useOptions.value = dictStore.useOptions;
	} else if(val=='组合结构'){
		// 层数处理
		csOptions.value = dictStore.csOptions.filter((item, index) => index == 2);
		params.value.cs = ''
		disabledcs.value = false;
		// 用途处理
		useOptions.value = [
            {
                value: '第Ⅰ类',
                label: '第Ⅰ类',
                children: [
                    {
                        value: '住宅',
                        label: '住宅'
                    },
                    {
                        value: '公寓',
                        label: '公寓'
                    },
                    {
                        value: '学生和职工集体宿舍',
                        label: '学生和职工集体宿舍'
                    },
                    {
                        value: '宾馆',
                        label: '宾馆'
                    },
                    {
                        value: '招待所',
                        label: '招待所'
                    },
                    {
                        value: '其他人员居住场所',
                        label: '其他人员居住场所'
                    }
                ]
            },
            {
                value: '第Ⅱ类',
                label: '第Ⅱ类',
                children: [
                    {
                        value: '办公室',
                        label: '办公室'
                    },
                ]
            },
        ]
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions.filter(item=>(item.value!='未设防'&&item.value!='自设防'));
	}else if(val=='砌体结构'){
		// 层数处理
		csOptions.value = dictStore.csOptions.filter((item, index) => index < 2);
		disabledcs.value = false;
		// 切换类型时，部分类型楼层没有就"9层以上"选项，则清空
		if (params.value.cs == '9层以上') {
			params.value.cs = ''
		}
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions;
	}else{
		// 层数处理
		disabledcs.value = true;
		csOptions.value = [];
		params.value.cs = ''
		// 用途
		if(val=='土木结构'||val=='木结构'||val=='其他'){
			useOptions.value = [
            {
                value: '第Ⅰ类',
                label: '第Ⅰ类',
                children: [
                    {
                        value: '住宅',
                        label: '住宅'
                    },
                    {
                        value: '其他人员居住场所',
                        label: '其他人员居住场所'
                    }
                ]
            },
            {
                value: '第Ⅲ类',
                label: '第Ⅲ类',
                children: [
                    {
                        value: '除I、II类以外',
                        label: '除I、II类以外'
                    }
                ]
            }
        ]
		if(val=='土木结构'){
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions.filter(item=>item.value=='未设防');
		yearsOptions.value = dictStore.yearsOptions.filter((item, index) => index < 4);
		// 切换类型时，年代--选项，则清空
		if (params.value.years == '2010-2016年'||params.value.years == '2016年以后') {
			params.value.years = ''
		}
		}else if(val=='其他'){
			fortificationOptions.value = dictStore.fortificationOptions.filter(item=>(item.value=='未设防'||item.value=='自设防'||item.value=='6度'));
		}
	}else{
			useOptions.value = [
            {
                value: '第Ⅱ类',
                label: '第Ⅱ类',
                children: [
                    {
                        value: '生产车间',
                        label: '生产车间'
                    },
                ]
            },
        ]
		}
	}
};
// 选择用途
const useChange = val => {
	const use = useOptions.value.find(item => item.value === val);
	if (use) {
		params.value.use1 = '';
		use1Options.value = use.children;
	}
};

// 模板下载
const importTemplate = (isBuild) => {
	// 导入建筑物易损性信息，取模板文件名称
	if (isBuild == 1) {
		downloadFileName.value = templateFileName.value;
	} else if (isBuild == 2) {
		downloadFileName.value = templateFileName1.value;
	}
	// 执行下载
	proxy.download(apiUrl.downloadExcel, { fileName: downloadFileName.value }, downloadFileName.value);
};
// 设置导出文件名和导出接口
const importParmsClick = (val) => {
	fileList.value = [];
	cityData.value = [];
	areaData.value = [];
	switch (val) {
		case 'buildVulner':
			outerVisible.value = true;
			proxy.resetForm("ruleFormRef");
			console.log('11111');
			ruleForm.value = {}
			downloadFileName.value = '建筑物易损性信息数据模板.xlsx';
			uploadFileUrl.value = apiUrl.uploadBvInformation;
			break;
		case 'brickStructure':
			dialogVisible.value = true;
			downloadFileName.value = '砖混结构参数信息数据模板.xlsx';
			uploadFileUrl.value = apiUrl.uploadPobStructure;
			break;
		case 'reinforConcrete':
			dialogVisible.value = true;
			downloadFileName.value = '钢筋混凝土结构参数信息数据模板.xlsx';
			uploadFileUrl.value = apiUrl.uploadRcpInformation;
			break;
		case 'highBuilding':
			dialogVisible.value = true;
			downloadFileName.value = '高层建筑参数信息数据模板.xlsx';
			uploadFileUrl.value = apiUrl.uploadHbpInformation;
			break;
		case 'seismicAnalysis':
			dialogVisible.value = true;
			downloadFileName.value = '概率地震易损性分析数据模板.xlsx';
			uploadFileUrl.value = apiUrl.uploadPsaData;
			break;
		default:
		case 'hubBuilding':
			buildVisible.value = true;
			proxy.resetForm("ruleFormBuildRef");
			ruleForm.value = {}
			textarea.value = '';
			downloadFileName.value = '';
			uploadFileUrl.value = apiUrl.uploadPsaData;
			break;
	}
}
const changeTypeOption = (value) => {
	textarea.value = '';
	if (value) {
		switch (value) {
			case '11':
				templateFileName1.value = '导入模板—水厂泵房-计算参数信息.xlsx'
				break;
			case '12':
				templateFileName1.value = '导入模板—重要发电厂房-计算参数信息.xlsx'
				break;
			case '13':
				templateFileName1.value = '导入模板—基站-计算参数信息.xlsx'
				break;
			case '14':
				templateFileName1.value = '导入模板—燃气门站场站-计算参数信息.xlsx'
				break;
			default:
				break;
		}
	} else {
		templateFileName1.value = ''
	}
}
// const changeTypeOption = (value) =>{
// 	ruleForm.value.structureType1 = ''
// 	ruleForm.value.structureType2 = ''
// 	structureTypeOptions1.value = []
// 	structureType1Options1.value = []
// 	if(!value){
// 	}else{
// 		ruleForm.value.structureType2 = ''
// 		structureType1Options1.value = []
// 		if(value=='1'){
// 			structureTypeOptions1.value = [{label:'钢筋混凝土框架结构',value:'钢筋混凝土框架结构'},{label:'砖砌体结构',value:'砖砌体结构'}]
// 		}else if(value=='2'){
// 			structureTypeOptions1.value = [{label:'钢混结构',value:'钢混结构'},{label:'砖混结构',value:'砖混结构'}]
// 		}else{
// 			structureTypeOptions1.value = [{label:'砌体结构',value:'砌体结构'},{label:'钢筋混凝土结构',value:'钢筋混凝土结构'}]
// 		}
// 	}
// }
const structureTypeChange1 = val => {
	ruleForm.value.structureType2 = ''
	if (val == '砌体结构') {
		structureType1Options1.value = [{ label: '砖混结构', value: '砖混结构' }]
	} else if (val == '钢筋混凝土结构') {
		structureType1Options1.value = [{ label: '框架结构', value: '框架结构' }, { label: '框架-剪力墙结构', value: '框架-剪力墙结构' }, { label: '剪力墙结构', value: '剪力墙结构' }]
	} else {
		structureType1Options1.value = []
	}
};
// 添加易损性矩阵信息
const onSaveBvInformation = () => {
	return saveBvInformation({
		"cbvInfoEntity": { ...params.value },
		"cbvInfoMatrixValueList": [...dataList.value]
	}).then(res => {
		const { code, data } = res;
		if (code == 200) {
			proxy.$modal.msgSuccess('添加易损性矩阵信息成功！');
		}
	}).catch(err => {
		console.log(err.message);
	})
}
// 添加易损性曲线信息
const onSaveBvInformationCurve = () => {
	return saveBvInformationCurve({
		"cbvInfoEntity": { ...params.value },
		"cbvInfoValueList": [...dataList.value]
	}).then(res => {
		const { code, data } = res;
		if (code == 200) {
			proxy.$modal.msgSuccess('添加易损性曲线信息成功！');
		}
	}).catch(err => {
		console.log(err.message);
	})
}

// 文件上传
// 移除前
const beforeRemove = () => {
	fileList.value = [];
};
// 上传前
const beforeUpload = (file) => {
	const fileSize = file.size / 1024 / 1024;
	if (fileSize > 200) {
		$message.error('文件大小不能超过200M!');
		return false;
	}
	const fileReg = /.xls|.xlsx/;
	if (!fileReg.test(file.name)) {
		$message.error('请选择.xls .xlsx格式文件');
		return false;
	}
	return true;
};
// 上传成功
const uploadSuccess = (response, uploadFile, uploadFiles) => {
	const { code, data, message } = response;
	if (code === 200) {
		proxy.$modal.msgSuccess("上传文件成功!");
		// 上传文件的数据列表
		if (data && Object.prototype.toString.call(data) == '[object Object]') {
			dataList.value = [{ ...data }];
		} else {
			dataList.value = data || [];
		}
		// 批量导入不显示二层弹框，单个导入显示二层弹框
		if (ruleForm.value.import === "1") {
			innerVisible.value = true;
		} else {
			// 关闭所有弹框
			closeAllDialog();
		}
	} else {
		fileList.value= [];
		dataList.value = [];
		proxy.$modal.msgError(message || "导入失败，请检查表头是否改动!");
	}
}
// 上传失败
const uploadError = (response, uploadFile, uploadFiles) => {
	proxy.$modal.msgError(response.message || "导入失败，请检查表头是否改动!");
}

// 挂载
onMounted(() => {
	// 获取行政区划数据
	getProvinceData();
});
</script>

<style lang="scss" scoped>
.wrapper {
	position: relative;

	h4 {
		font-size: 20px;
		font-weight: bold;
		color: #107ce5;
		text-align: center;
	}

	.row-bgs {
		width: 100%;
		display: flex;
		margin-bottom: 30px;

		&:last-child {
			margin-bottom: 0;
		}

		div {
			width: 360px;
			height: 150px;
			display: flex;
			justify-content: center;
		}

		.buildVulner {
			background: url("../../../../assets/importImages/jzwysx.png");
		}

		.brickStructure {
			background: url("../../../../assets/importImages/zhjg.png");
		}

		.reinforConcrete {
			background: url("../../../../assets/importImages/gjhnt.png");
		}

		.highBuilding {
			background: url("../../../../assets/importImages/gcjz.png");
		}

		.seismicAnalysis {
			background: url("../../../../assets/importImages/dzysxfx.png");
		}

		.hubBuilding {
			background: url("../../../../assets/importImages/snjz.png")no-repeat;
			background-size: 360px 150px;
		}
	}

	.downloadModel {
		font-size: 16px;
		line-height: 60px;

		span {
			color: #107ce5;
			cursor: pointer;
		}
	}

	.el-form-item {
		margin-right: 0;
	}

	.new-fileBtn {
		margin: 0px 10px 0px 40px;
	}

	.new-filesTextArea {
		width: 216px;
	}
}
</style>
